package com.example.tourstor.database;

import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager {


    public static final String DRIVER = "com.mysql.jdbc.Driver";
//    public static final String USER = "root";
//    public static final String PASSWORD = "Dyf_980920";
    public static final String USER = "citi";
    public static final String PASSWORD = "swufe";
    public static final String URL = "jdbc:mysql://118.24.36.177:3306/tourstor";
//public static final String URL = "jdbc:mysql://192.168.43.211:3306/tour?useUnicode=true&amp;characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&relaxAutoCommit=true&zeroDateTimeBehavior=convertToNull";
    static DBManager dbManager = null;
    Connection conn = null;
    public Statement stmt = null;

    private static final String TAG = "DBManager";

    public static DBManager createInstance() {

        if (dbManager == null) {
            dbManager = new DBManager();
            dbManager.initDB();
            Log.i(TAG, "createInstance: new database");
        }
        return dbManager;
    }

    private void initDB() {
        try {
            Class.forName(DRIVER);
            Log.i(TAG, "initDB: init database");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void connectDB() {
        Log.i(TAG, "connectDB: Connecting to database ...");
        try {
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            stmt = conn.createStatement();
            Log.i(TAG, "connectDB: connect database : success");
        } catch (SQLException e) {
            Log.i(TAG, "connectDB: connect database : error");
            e.printStackTrace();
        }
    }

    public void closeDB() {
        Log.i(TAG, "closeDB: Close connection to database ...");
        if (conn != null) {
            try {
                conn.close();
                Log.i(TAG, "closeDB: close connection : success");
            } catch (SQLException e) {
                Log.i(TAG, "closeDB: close connection : error");
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
                Log.i(TAG, "closeDB: close statement : success");
            } catch (SQLException e) {
                Log.i(TAG, "closeDB: close statement : error");
                e.printStackTrace();
            }
        }
        Log.i(TAG, "closeDB: close connection : success");
    }

}
